package com.psa.system;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.psa.adapter.SqlObjectListAdapter;
import com.psa.dialog.CustomerInterchangeDialog;
import com.psa.element.Customer;
import com.psa.element.District;
import com.psa.element.ISqlObject;
import com.psa.element.Interchange;
import com.psa.tool.DBTool;
import com.psa.tool.ExitApplication;
import com.psa.tool.RequestManager;
import com.psa.tool.SystemStatus;
import com.wxw.BaseLibrary.element.JsonObject;
import com.wxw.BaseLibrary.tool.ActivityTool;
import net.duohuo.dhroid.ioc.InjectUtil;
import net.duohuo.dhroid.ioc.annotation.InjectView;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author david
 * @date 2014-10-20
 */
public class CustomerManagerActivity extends BaseActivity {
    @InjectView(id = R.id.search_customer_reset, click = "onClick")
    private Button btn_search_customer_reset;
    @InjectView(id = R.id.search_customer, click = "onClick")
    private Button btn_search_customer;
    @InjectView(id = R.id.btn_pending, click = "onClick")
    private Button btn_pending;
    @InjectView(id = R.id.et_customer_name)
    private EditText et_customer_name;
    @InjectView(id = R.id.et_customer_id)
    private EditText et_customer_id;
    @InjectView(id = R.id.sp_customer_district, itemSelected = "onItemSelected", nothingSelected = "onNothingSelected")
    private Spinner sp_customer_district;
    @InjectView(id = R.id.lv_customers, itemClick = "onItemClick")
    private ListView lv_customers;

    private List<District> districts = new ArrayList<District>();
    private List<ISqlObject> customers = new ArrayList<ISqlObject>();
    private SqlObjectListAdapter adapter = null;
    private String whereName,whereID,whereDistrict;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityTool.hideTitle(this);
        ActivityTool.fullScreen(this);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.customer_manager_layout);
        InjectUtil.inject(this);
        tv_head_title.setText(getString(R.string.customer_manager_code_title));
        btn_back.setText(getString(R.string.customer_manager_code_btn_back));
        btn_next.setBackgroundResource(R.drawable.button_style);
        btn_next.setText(getString(R.string.customer_manager_code_btn_next));
        refreshDistricts();
        adapter = new SqlObjectListAdapter(this, customers);
        lv_customers.setAdapter(adapter);
        RequestManager.getRequestManager().addGeneralEventListener(this);
        tv_info.setText(SystemStatus.getReqCount());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            RequestManager.getRequestManager().removeGeneralEventListener(this);
            setResult(1);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_next:
                SystemStatus.currentCustomer = null;
                startActivityForResult(new Intent(this, CustomerEditorActivity.class), 0);
                break;
            case R.id.search_customer_reset:
                et_customer_name.setText("");
                et_customer_id.setText("");
                et_customer_name.requestFocus();
                break;
            case R.id.search_customer:
                refreshCustomers();
                break;
            case R.id.btn_pending:
                CustomerInterchangeDialog interchangeDialog = new CustomerInterchangeDialog(this);
                interchangeDialog.setOnInterchangeItemClickListener(new CustomerInterchangeDialog.OnInterchangeItemClickListener() {
                    @Override
                    public void onItemClick(CustomerInterchangeDialog dialog, Interchange interchange) {
                        JsonObject jsonObject = new JsonObject(interchange.Contents);
                        if (jsonObject!=null && jsonObject.getProperty("ID")!=null){
                            SystemStatus.currentCustomer = Customer.getCustomer(jsonObject.getProperty("ID").getValue());
                            Intent intent = new Intent(CustomerManagerActivity.this, CustomerEditorActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("interchange", interchange.toJson());
                            intent.putExtras(bundle);
                            startActivityForResult(intent, 1);
                        }
                    }
                });
                interchangeDialog.show();
                break;
            default:
                break;
        }
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        adapter.setIndex(i);
        SystemStatus.currentCustomer = (Customer)customers.get(i);
        startActivityForResult(new Intent(this, CustomerActivity.class), 0);
    }

    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        try {
            whereDistrict = "'" + ((District) districts.get(i)).ID.trim() + "'";
            CustomerManagerActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshCustomers();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            whereDistrict = "";
        }
    }

    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void finished(Object sender, String eventContent) {
        if (sender instanceof RequestManager){
//            SystemStatus.ReqCount = eventContent;
            CustomerManagerActivity.this.runOnUiThread(showRequestChangedCallback);
        } else {

        }
    }

    private void refreshDistricts(){
        try {
            Cursor cursor = DBTool.getInstance().query("Select B.* From (Select Distinct DistrictID From OperatorCustomer) A Left Join District B "
                    + "On A.DistrictID=LTRIM(RTRIM(B.ID)) Order By ID");
            District district = new District();
            while ((district = (District) district.full(cursor)) != null) {
                districts.add(district);
            }
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            Log.d(SystemStatus.TAG, e.getMessage());
            return;
        }
        com.wxw.BaseLibrary.adapter.SpinnerAdapter adapter = new com.wxw.BaseLibrary.adapter.SpinnerAdapter<District>(this, -1, districts, R.drawable.dropdown);
        sp_customer_district.setAdapter(adapter);
    }

    private void refreshCustomers(){
        if (et_customer_name.getText().toString().trim().equals("")) {
            whereName="";
        } else {
            whereName=" And a.ChineseName Like '%" + et_customer_name.getText().toString().trim()+"%' ";
        }

        if (et_customer_id.getText().toString().trim().equals("")) {
            whereID="";
        } else {
            whereID=" And a.ID Like '%" + et_customer_id.getText().toString().trim()+"%' ";
        }
        customers.clear();
        Cursor cursor = DBTool.getInstance().query("Select Distinct a.* From Customer a Left Join OperatorCustomer b On a.ID=b.CustomerID "
                + "Where b.DistrictID=" + whereDistrict
                + " " + whereID + whereName + " Order By b.SeqNo");
        Customer customer = new Customer();
        while ((customer = (Customer)customer.full(cursor)) != null) {
            customers.add(customer);
        }
        adapter.notifyDataSetChanged();
    }
}
